package server.servlets;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import player.Player;


import commons.Manager;
import commons.User;
import server.filters.RestrictedPagesToConnectedUser;

/**
 * Servlet that manage the advanced controls for OMXPLAYER
 * @author Romain Pellerin
 */
public class Controls extends HttpServlet {

	private static final long serialVersionUID = -6676921078519082626L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user;
		if ((user = RestrictedPagesToConnectedUser.getUserIfConnected(request)) != null) {
			if (user.isAdmin()) {
				sendAction(request);
				this.getServletContext().getRequestDispatcher("/WEB-INF/jsp_pages/controls.jsp").forward(request, response);
				return;
			}
		}
		closePopup(response);
	}

	/**
	 * Method that closes the current popup
	 * @param response The HTTP response
	 * @throws IOException throw when something went wrong and we don't know why
	 */
	private void closePopup(HttpServletResponse response) throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding( "UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset=\"utf-8\" />");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>Forbidden</h1>");
		out.println("<script>window.close();</script>");
		out.println("</body>");
		out.println("</html>");
	}

	/**
	 * Executes an action from the parameter 'action' in URL (if exists)
	 * @param request The {@link HTTPServletRequest} where '?action=' is
	 */
	private void sendAction(HttpServletRequest request) {
		String action = request.getParameter("action");
		if (action != null && !action.trim().isEmpty()) {
			String command = null;
			command = Player.OmxPlayerCommands.getCommand(Integer.valueOf(action));
			if (command != null) {
				System.err.println(command);
				Manager.getInstance().action(command);
			}

		}
	}
}
